#!/bin/sh

#
# Test a file to a FAT file system without specifying the filename for a fat_write.
# Note: This is a copy/paste of 012_fat_write.test with the fat_write call modified.
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}
file-resource subdir/1K.bin {
	host-path = "${TESTFILE_1K}"
}

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
                fat_mkdir(\${BOOT_PART_OFFSET}, "subdir")
        }
        on-resource 1K.bin { fat_write(\${BOOT_PART_OFFSET}) }
        on-resource subdir/1K.bin { fat_write(\${BOOT_PART_OFFSET}) }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

EXPECTED_OUTPUT=$WORK/expected.out
ACTUAL_OUTPUT=$WORK/actual.out

cat >$EXPECTED_OUTPUT << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/

subdir       <DIR>     1980-01-01   0:00
1K       bin      1024 1980-01-01   0:00
         2 files               1 024 bytes
                          38 907 904 bytes free

EOF

# Check that the directory looks right
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check the contents of the file
mcopy -n -i $WORK/fwup.img@@32256 ::/1K.bin $WORK/actual.1K.bin
diff $TESTFILE_1K $WORK/actual.1K.bin

mcopy -n -i $WORK/fwup.img@@32256 ::/subdir/1K.bin $WORK/actual2.1K.bin
diff $TESTFILE_1K $WORK/actual2.1K.bin

# Check the FAT file format using fsck
dd if=$WORK/fwup.img skip=63 of=$WORK/vfat.img
$FSCK_FAT $WORK/vfat.img

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
